package com.wang.interview.threads;

import java.util.concurrent.*;

/**
 * @author: wang
 * @date: 2021/7/23 09:07
 * @description:
 */
public class CallableTest implements Callable<Object> {

    private int i;

    @Override
    public Object call(){
        System.out.println(i++);
        return Thread.currentThread().getName();
    }

//    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        FutureTask<Object> ft = new FutureTask<Object>(new CallableTest());
//        /*new Thread(ft,"A").start();
//        new Thread(ft,"B").start(); // 多次调用也只会执行一次
//        System.out.println(ft.get());     // get方法会阻塞
//        System.out.println("你好");*/
//        ExecutorService pool = Executors.newSingleThreadExecutor();
//        pool.execute(ft);
//        Future<?> submit = pool.submit(ft);
//        submit.get();
//    }
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        /*ExecutorService pool = Executors.newCachedThreadPool();
        FutureTask<String> task = new FutureTask<>(() -> "你大爷");
        Future<?> submit = pool.submit(task);
        System.out.println(submit.get());
        pool.shutdown();*/
        ExecutorService pool = Executors.newFixedThreadPool(2);
        FutureTask<Object> task = new FutureTask<>(() -> Thread.currentThread().getName());
        pool.submit(task);
        Object o = task.get(); // 注意：要想获得返回值必须要调用 task的get 方法。submit返回的future的get方法无效
        System.out.println(o);
        System.out.println(Thread.currentThread().getName());
        pool.shutdown();

    }
}

